package com.zzyl.nursing.service.impl;

import java.util.*;
import java.time.*;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceResponse;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDataDto;
import com.zzyl.nursing.dto.DevicePropertyDto;
import com.zzyl.nursing.dto.FamilyMemberAddDto;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IElderService elderService;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient iotdAClient;
    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 小程序端登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if (ObjectUtil.isEmpty(familyMember)) {
            familyMember = FamilyMember
                    .builder()
                    .openId(openid)
                    .build();
        }

        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(familyMember, phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("userName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }


    /**
     * 保存或更新用户
     *
     * @param familyMember
     * @param phone
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone, 7, 11);
        familyMember.setName(nickName);
        //保存
        save(familyMember);

    }


    /**
     * 绑定老人
     *
     * @param dto
     * @return
     */
    @Override
    public int bind(FamilyMemberAddDto dto) {
        //获取当前登录人
        Long userId = UserThreadLocal.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            throw new BaseException("请先登录");
        }

        //判断老人是否存在
        Elder elder = elderService.getOne(
                Wrappers.<Elder>lambdaQuery()
                        .eq(Elder::getIdCardNo, dto.getIdCard())
                        .eq(Elder::getName, dto.getName())
        );

        if (ObjectUtil.isEmpty(elder)) {
            throw new BaseException("未找到对应的老人信息");
        }

        // 检查是否已经绑定过
        FamilyMemberElder existingRelation = familyMemberElderMapper.selectOne(
                Wrappers.<FamilyMemberElder>lambdaQuery()
                        .eq(FamilyMemberElder::getElderId, elder.getId())
                        .eq(FamilyMemberElder::getFamilyMemberId, userId)
        );


        if (ObjectUtil.isNotEmpty(existingRelation)) {
            throw new BaseException("该老人已经绑定过");
        }

        //绑定老人和家属
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setRemark(dto.getRemark());
        familyMemberElder.setCreateTime(new Date());
        familyMemberElder.setCreateBy(userId.toString());
        familyMemberElder.setUpdateTime(new Date());
        familyMemberElder.setUpdateBy(userId.toString());
        familyMemberElderMapper.insert(familyMemberElder);

        //判断该用户是否有其他家人称呼重复,查询中间表
        long count = familyMemberElderMapper.selectCount(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId).eq(FamilyMemberElder::getRemark, dto.getRemark()));
        if (count > 0) {
            throw new BaseException("该称呼已存在");
        }

        return 1;
    }

    /**
     * 查看已绑定家人列表（分页查询）
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<MemberVO> listByPage(Integer pageNum, Integer pageSize) {
        //获取当前登录人
        Long familyMemberId = UserThreadLocal.getUserId();
        //查询已绑定家人列表
        List<MemberVO> memberVO = new ArrayList<>();
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectList(
                Wrappers.<FamilyMemberElder>lambdaQuery()
                        .eq(FamilyMemberElder::getFamilyMemberId, familyMemberId)
        );
        familyMemberElders.forEach(familyMemberElder -> {
            Long elderId = familyMemberElder.getElderId();
            Elder elder = elderMapper.selectById(elderId);
            MemberVO vo = new MemberVO();
            vo.setMid(String.valueOf(familyMemberId));
            vo.setMremark(familyMemberElder.getRemark());
            vo.setElderId(String.valueOf(elderId));
            vo.setName(elder.getName());
            vo.setImage(elder.getImage());
            vo.setBedNumber(elder.getBedNumber());

            //获取房间类型名称，通过床号查询
            Long bedId = elder.getBedId();
            Bed bed = bedMapper.selectBedById(bedId);
            Long roomId = bed.getRoomId();
            Room room = roomMapper.selectById(roomId);
            vo.setTypeName(room.getTypeName());

            //获取设备信息
            LambdaQueryWrapper<Device> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Device::getBindingLocation, elder.getId());
            lqw.eq(Device::getLocationType, 0);
            lqw.eq(Device::getPhysicalLocationType, -1);
            Device device = deviceMapper.selectOne(lqw);
            //判断设备是否存在
            if (ObjectUtil.isNotEmpty(device)) {
                vo.setIotId(device.getIotId());
                vo.setDeviceName(device.getDeviceName());
                vo.setProductKey(device.getProductKey());
            }

            //将数据添加到集合中
            memberVO.add(vo);

        });

        return memberVO;
    }

    /**
     * 查询健康数据
     *
     * @param dto
     * @return
     */
    @Override
    public DevicePropertyVo queryDevicePropertyStatus(DevicePropertyDto dto) {
        String deviceName = dto.getDeviceName();
        String productKey = dto.getProductKey();

        DevicePropertyVo response = new DevicePropertyVo();
        Map<String, List<PropertyStatusInfo>> map = new HashMap<>();
        List<PropertyStatusInfo> propertyStatusInfoList = new ArrayList<>();
        //查询设备
        List<Device> devices = deviceMapper.selectList(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceName)
                .eq(Device::getProductKey, productKey));
        //遍历设备
        devices.forEach(device -> {
            String iotId = device.getIotId();
            //根据iotid查询iot平台中的设备数据
            ShowDeviceRequest request = new ShowDeviceRequest();
            request.setDeviceId(iotId);
            ShowDeviceResponse showDeviceResponse;
            try {
                showDeviceResponse = iotdAClient.showDevice(request);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException("物联网接口 - 查询设备详情，调用失败");
            }


            Object deviceDataObj = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
            if (deviceDataObj == null) {
                return;
            }

            String deviceDataList;
            if (deviceDataObj instanceof String) {
                deviceDataList = (String) deviceDataObj;
            } else if (deviceDataObj instanceof List) {
                // 如果是List类型，转换为JSON字符串
                deviceDataList = JSONUtil.toJsonStr(deviceDataObj);
            } else {
                // 其他情况，转换为字符串
                deviceDataList = deviceDataObj.toString();
            }

            if (StringUtils.isEmpty(deviceDataList)) {
                return;
            }

            List<DeviceData> dataList = JSONUtil.toList(deviceDataList, DeviceData.class);
            dataList.forEach(data -> {
                if (deviceName.equals(data.getDeviceName())) {
                    // 格式化DataValue保留1位小数
                    String formattedValue = String.format("%.1f",
                            Double.parseDouble(data.getDataValue()));
                    propertyStatusInfoList.add(new PropertyStatusInfo(
                            data.getFunctionId(),
                            data.getFunctionId(),
                            data.getFunctionId(),
                            data.getAlarmTime().toString(),
                            data.getFunctionId(),
                            formattedValue
                    ));
                }
            });
        });

        map.put("propertyStatusInfo", propertyStatusInfoList);
        response.setList(map);

        return response;
    }

    /**
     * 解绑老人
     *
     * @param elderId
     */
    @Override
    public void removeElder(Long elderId) {
        Long userId = UserThreadLocal.getUserId();
        LambdaQueryWrapper<FamilyMemberElder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FamilyMemberElder::getFamilyMemberId, userId).eq(FamilyMemberElder::getElderId, elderId);
        int result = familyMemberElderMapper.delete(wrapper);
        if (result <= 0) {
            throw new BaseException("解绑失败");
        }
    }


    /**
     * 查询设备数据按天查询
     *
     * @param deviceDataDto
     * @return
     */
    @Override
    public List<DeviceDataByDayVo> queryByDay(DeviceDataDto deviceDataDto) {
        // 将毫秒时间戳转换为 LocalDate
        LocalDate startDate = Instant.ofEpochMilli(deviceDataDto.getStartTime())
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        // 构建日期范围查询条件
        // 当天00:00:00
        LocalDateTime startDateTime = startDate.atStartOfDay();
        // 当天23:59:59
        LocalDateTime endDateTime = startDate.atTime(23, 59, 59);

        // 查询数据
        LambdaQueryWrapper<DeviceData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceData::getIotId, deviceDataDto.getIotId())
                .eq(DeviceData::getFunctionId, deviceDataDto.getFunctionId())
                .between(DeviceData::getAlarmTime, startDateTime, endDateTime)
                .orderByAsc(DeviceData::getAlarmTime);

        List<DeviceData> deviceDataList = deviceDataMapper.selectList(wrapper);

        // 按小时分组并计算平均值
        Map<Integer, List<DeviceData>> hourlyDataMap = new HashMap<>();

        // 初始化24小时的数据
        for (int i = 0; i < 24; i++) {
            hourlyDataMap.put(i, new ArrayList<>());
        }

        // 将数据按小时分组
        for (DeviceData data : deviceDataList) {
            int hour = data.getAlarmTime().getHour();
            hourlyDataMap.get(hour).add(data);
        }

        // 计算每小时平均值并构建返回结果
        List<DeviceDataByDayVo> result = new ArrayList<>();

        for (int hour = 0; hour < 24; hour++) {
            List<DeviceData> hourlyData = hourlyDataMap.get(hour);
            DeviceDataByDayVo vo = new DeviceDataByDayVo();

            if (!hourlyData.isEmpty()) {
                // 计算该小时数据的平均值
                double sum = 0;
                int validCount = 0;

                for (DeviceData data : hourlyData) {
                    try {
                        double value = Double.parseDouble(data.getDataValue());
                        sum += value;
                        validCount++;
                    } catch (NumberFormatException e) {
                        // 忽略无法转换为数字的数据
                        log.warn("无法解析数据值: {}", data.getDataValue());
                    }
                }

                if (validCount > 0) {
                    double average = sum / validCount;
                    // 四舍五入到一位小数
                    double roundedAverage = Math.round(average * 10) / 10.0;
                    vo.setDataValue(roundedAverage);
                } else {
                    vo.setDataValue(0.0);
                }
            } else {
                vo.setDataValue(0.0);
            }

            // 设置时间格式为 HH:00
            vo.setDateTime(LocalTime.of(hour, 0));
            result.add(vo);
        }

        return result;
    }

    /**
     * 按周查询
     *
     * @param deviceDataDto
     * @return
     */
    @Override
    public List<DeviceDataByWeekVo> queryByWeek(DeviceDataDto deviceDataDto) {
        // 将毫秒时间戳转换为 LocalDate
        LocalDate startDate = Instant.ofEpochMilli(deviceDataDto.getStartTime())
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        LocalDate endDate = Instant.ofEpochMilli(deviceDataDto.getEndTime())
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        // 构建日期范围查询条件
        // 当天00:00:00
        LocalDateTime startDateTime = startDate.atStartOfDay();
        // 当天23:59:59
        LocalDateTime endDateTime = endDate.atTime(23, 59, 59);

        // 查询数据
        LambdaQueryWrapper<DeviceData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceData::getIotId, deviceDataDto.getIotId())
                .eq(DeviceData::getFunctionId, deviceDataDto.getFunctionId())
                .between(DeviceData::getAlarmTime, startDateTime, endDateTime)
                .orderByAsc(DeviceData::getAlarmTime);

        List<DeviceData> deviceDataList = deviceDataMapper.selectList(wrapper);
        Map<LocalDate, List<DeviceData>> dailyDataMap = new HashMap<>();

        // 初始化日期范围内的每一天
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            dailyDataMap.put(date, new ArrayList<>());
        }

        // 将数据按实际日期分组
        for (DeviceData data : deviceDataList) {
            LocalDate dataDate = data.getAlarmTime().toLocalDate();
            // 检查数据日期是否在查询范围内
            if (dailyDataMap.containsKey(dataDate)) {
                dailyDataMap.get(dataDate).add(data);
            }
        }

        // 计算每天平均值并构建返回结果
        List<DeviceDataByWeekVo> result = new ArrayList<>();
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            List<DeviceData> dailyData = dailyDataMap.get(date);
            DeviceDataByWeekVo vo = new DeviceDataByWeekVo();

            if (!dailyData.isEmpty()) {
                // 计算该天数据的平均值
                double sum = 0;
                int validCount = 0;

                for (DeviceData data : dailyData) {
                    try {
                        double value = Double.parseDouble(data.getDataValue());
                        sum += value;
                        validCount++;
                    } catch (NumberFormatException e) {
                        log.warn("无法解析数据值: {}", data.getDataValue());
                    }
                }
                if (validCount > 0) {
                    double average = sum / validCount;
                    double roundedAverage = Math.round(average * 10) / 10.0;
                    vo.setDataValue(roundedAverage);
                } else {
                    vo.setDataValue(0.0);
                }
            } else {
                vo.setDataValue(0.0);
            }

            // 设置实际日期
            vo.setDateTime(date);

            result.add(vo);
        }

        return result;

    }


}
